package upc.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import jakarta.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class OSSUtil {
    //阿里云API的外网域名
    public static final String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    //阿里云API的密钥Access Key ID
    public static final String ACCESS_KEY_ID = "LTAI5tJqCW4zyvURnNr9RsSj";
    //阿里云API的密钥Access Key Secret
    public static final String ACCESS_KEY_SECRET = "3mcQ9Etp53SOTyVPtDOm3LT7HWr1cc";
    //阿里云API的bucket名称
    public static final String BACKET_NAME = "meet-assistant";

    /**
     * 下载并压缩返回
     *
     * @param fileNames 文件名称的集合
     * @param response  响应
     */
    public static void getFileToZip(List<String> fileNames, HttpServletResponse response) {
        try {
            OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            //压缩包名称
            String zipName = "file.zip";
            //创建临时文件
            File zipFile = File.createTempFile("file", ".zip");
            FileOutputStream fileOutputStream = new FileOutputStream(zipFile);

            /**
             * 作用是为任何outputstream产生校验和
             * 第一个参数是制定产生校验和的输出流，第二个参数是指定checksum类型（Adler32（较快）和CRC32两种）
             */
            CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream, new Adler32());
            //用于将数据压缩成zip文件格式
            ZipOutputStream zos = new ZipOutputStream(cos);

            for (String fileName : fileNames) {
                //获取object，返回结果ossObject对象
                OSSObject ossObject = ossClient.getObject(BACKET_NAME, fileName);
                //读取object内容，返回
                InputStream inputStream = ossObject.getObjectContent();
                // 对于每一个要被存放到压缩包的文件，都必须调用ZipOutputStream对象的putNextEntry()方法，确保压缩包里面文件不同名
                zos.putNextEntry(new ZipEntry(fileName));
                int bytesRead = 0;
                // 向压缩文件中输出数据
                while ((bytesRead = inputStream.read()) != -1) {
                    zos.write(bytesRead);
                }
                inputStream.close();
                zos.closeEntry(); // 当前文件写完，定位为写入下一条项目
            }
            zos.close();
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + zipName);

            FileInputStream fis = new FileInputStream(zipFile);
            BufferedInputStream buff = new BufferedInputStream(fis);
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            byte[] car = new byte[1024];
            int l = 0;
            while (l < zipFile.length()) {
                int j = buff.read(car, 0, 1024);
                l += j;
                out.write(car, 0, j);
            }
            // 关闭流
            fis.close();
            buff.close();
            out.close();

            ossClient.shutdown();
            // 删除临时文件
            zipFile.delete();
        } catch (Exception e) {

        }
    }
}